#include "libline.h"

void fb(void * data)
{
}

ecv_lua * ecv_lua_initblocking()
{
  ecv_lua * llua = malloc(sizeof(ecv_lua));

  llua->ifaceout = malloc(sizeof(ecv_luaiface));
  llua->ifaceout->params = bk_clientinit(LUAIFACEPORTI, "localhost");
  llua->ifaceout->params->callback = fb;
  llua->ifaceout->readsize = ECV_MAGICK;
  llua->ifaceout->state = ECVLIB_ASK;
  printf ("connecting to localhost:%i\n", LUAIFACEPORTI);
  while (bk_clientconnect(llua->ifaceout->params)!=0)
    {
      sleep(1);
      printf ("trying to connect to ecv\n");
    }
  return llua;
}

int ecv_lua_step(ecv_lua * m_lua)
{
  ecv_inetp inetp;
  sockbuf * sb;
  int req;
  int sz;
  usleep(200000);
  switch (m_lua->ifaceout->state)
    {
    case ECVLIB_ASK:
      printf ("case ask\n");
      inetp.name = ECV_DATAREQUEST;
      inetp.data = NULL;
      bk_writetoserver (m_lua->ifaceout->params->sock, &(inetp.name), sizeof(int));
      m_lua->ifaceout->state = ECVLIB_WAIT;
      //      bk_serverstep(m_lua->ifaceout->params, m_lua->ifaceout->readsize);
      break;
    case ECVLIB_WAIT:
      sz = read (m_lua->ifaceout->params->sock, &req, sizeof(int));
      //      printf ("read sz = %i bytes, req = %i\n", sz, req);
      if (sz>0)
	{
	  switch (req)
	    {
	    case ECV_DATAREPLY:
	      sz = read (m_lua->ifaceout->params->sock, &req, sizeof(int));
	      //	      printf ("read sz = %i bytes, req = %i\n", sz, req);
	      if (sz>0)
		{
		  m_lua->ifaceout->offset = req;
		  m_lua->ifaceout->state = ECVLIB_ASK;
		}
	      break;
	    default:
	      break;
	    }
	}
      break;
    default:
      printf ("defaulted\n");
      break;
    }
  return 0;
}

int ecv_lua_finalize(ecv_lua * m_lua)
{
  bk_clientfinalize(m_lua->ifaceout->params);
  free(m_lua->ifaceout);
  /*  bk_serverfinalize(m_lua->ifacein->params);
  free(m_lua->ifacein);
  */
  free(m_lua);

  return 0;
}

double ecv_lua_getoffset(ecv_lua * m_lua)
{
  return (double)m_lua->ifaceout->offset;
}

